package com.manong.aspect;

import com.manong.dao.ActionLogMapper;
import com.manong.entity.ActionLog;
import com.manong.service.ActionLogService;
import com.manong.utils.JwtUtils;
import com.manong.utils.Result;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class AutoFillAspect {
    @Autowired
    private ActionLogService actionLogService;
    @Autowired
    private HttpServletRequest request;
    @Resource
    private JwtUtils jwtUtils;
    @Around("@annotation(autoFill)")
    public Object logAround(ProceedingJoinPoint joinPoint, AutoFill autoFill) throws Throwable {
        // 1.获取注解参数
        String menu = autoFill.menu();
        String type = autoFill.type();

        // 2.获取当前用户
        String token = request.getHeader("token");
        String username = jwtUtils.getUsernameFromToken(token);

        // 3.初始化日志对象
        ActionLog actionLog = new ActionLog();
        actionLog.setUsername(username);
        actionLog.setLabel(menu);
        actionLog.setLabelType(type);
        actionLog.setActionTime(new Date());

            // 4.执行原方法
            Object result = joinPoint.proceed();
            if(result instanceof Result){
                Result res = (Result) result;
                if(res.getSuccess()){
                    actionLog.setStatus('0'); // 1表示成功
                    actionLog.setMsg(res.getMessage()); // 记录返回消息
                }else{
                    actionLog.setStatus('1'); // 0表示失败
                    actionLog.setMsg("操作失败：" + res.getMessage());
                }
            }
//            // 5.记录成功状态和信息
//            actionLog.setStatus('1'); // 1表示成功
//            if (logResult && result instanceof Result) {
//                Result res = (Result) result;
//                actionLog.setMsg(res.getMessage()); // 记录返回消息
//            }
//            return result;
//
//            // 6.记录失败状态和信息
//            actionLog.setStatus('0'); // 0表示失败
//            actionLog.setMsg("操作失败：" + e.getMessage());
//            throw e; // 继续抛出异常
            // 7.保存日志
            actionLogService.save(actionLog);
        return result;
    }
}
